import re
import logging
import random

from flask import Blueprint, jsonify
from flask import g
from flask import current_app
from flask import make_response
from flask import session
from flask import render_template
from flask import request
from hjutils.image_storage import image_storage

from ihome_tenancy.models import User
from ihome_tenancy.utils import qiniu_sdk

from ihome_tenancy.utils.captcha.captcha import captcha
from ihome_tenancy import redis_store, db
from ihome_tenancy.models import User
from ihome_tenancy.utils.my_decorators import is_login
from ihome_tenancy.utils.qiniu_sdk import put_qiniu
from ihome_tenancy.utils.response_code import RET, ret_map
# from ihome_tenancy.utils.yuntongxun.sms import CCP #导入报错

user_blueprint = Blueprint('user',__name__)

@user_blueprint.route('/user/send_sms')
def sms_code():
    #接受数据
    # dict_data=request.json
    # print(dict_data)
    imageCodes=request.args.get("imageCode")
    print(imageCodes)
    print(session['image_code'])
    mobile=request.args.get("mobile")
    #数据判空
    try:
        user = User.query.filter(User.phone == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询用户失败")
    if user:
        return jsonify(code=RET.PARAMERR, msg='手机号码已存在')
    if not all([mobile,imageCodes]):
        return jsonify(code=RET.PARAMERR,msg='参数不全')
    if not imageCodes.lower() == session['image_code'].lower() :
        return jsonify(code=RET.PARAMERR,msg='验证码错误')
    if not re.match(r'1[3-9]\d{9}',mobile):
        return jsonify(code=RET.PARAMERR,msg='手机格式错误')
    #生成验证码

    sms_code= random.randint(0 ,999999)
    print(sms_code)
    session['sms_code']=sms_code
    session['mobile']=mobile
    #云通讯
    # ccp=CCP()
    # result=ccp.send_template_sms(mobile,[sms_code,5],1)
    #
    # if result==-1:
    #     return jsonify(error=RET.PARAMERR,msg='发送短信失败')
    #发送成功
    redis_store.set("sms_code:%s"%mobile,sms_code,300)

    return jsonify(code=RET.OK,msg='发送成功' ,)

@user_blueprint.route('/user/user_register',methods=['POST'])
def user__register():
    dict_data = request.form
    mobile = dict_data.get('mobile') #电话
    phonecode = dict_data.get('phonecode') #短信验证码
    password = dict_data.get('password') #密码
    #
    print(phonecode)
    print(session['sms_code'])

    if not int(session['mobile']) == int(mobile):
        return jsonify(code=RET.DATAERR, msg="手机号填写错误")
    if not int(session['sms_code']) == int(phonecode):
        print(session['sms_code'] , phonecode)
        return jsonify(code=RET.DATAERR, msg="图片验证码填写错误")
    # print(mobile,phonecode,password)
    try:
        user = User()
        user.name = mobile
        user.password = password
        user.phone = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="注册失败")

    # session.pop("sms_code", None)
    # session.pop("Content-type", None)
    return jsonify(code=RET.OK, msg="注册成功")

@user_blueprint.route('/user/yzm')
def user_yzm():
    name, text, image_code = captcha.generate_captcha()

    session['image_code'] = text
    response = make_response(image_code)
    response.headers['Content-type']= 'image/jpeg'
    print(text)
    return response

@user_blueprint.route('/user/session')
@is_login
def user_session():
    # user_id = session.get("user_id")
    # if not user_id:
    #     return jsonify(code=RET.NODATA, msg="用户未登录")
    # else:
    #     return jsonify(code=RET.OK, msg="用户已登录")
    user = g.user
    # 　返回数据
    return jsonify(user=user.to_basic_dict(), code=RET.OK)


@user_blueprint.route('/user/', methods=['PUT'])
@is_login
def user_profile():
    """修改个人信息（用户名和头像）"""
    # 1 获取参数
    data_dict = request.form
    print(data_dict)
    user = g.user

    # 2 修改头像
    if 'avatar1' in data_dict:
        try:
            # 获取头像文件
            file_content = request.files.get('avatar')

            # mime-type:国际规范，表示文件的类型，如text/html,text/xml,image/png,image/jpeg..
            # 判断是否是图片类型文件
            if not re.match('image/.*', file_content.mimetype):
                return jsonify(code=RET.PARAMERR, msg='文件类型错误')
        except Exception as e:
            logging.error('获取头像图片文件错误')
            return jsonify(code=RET.PARAMERR, msg='获取头像图片文件错误')

        # 将图片上传到七牛云
        avatar_url = put_qiniu(file_content)

        # 保存用户的头想信息
        try:
            user.avatar = avatar_url
            user.add_update()
        except Exception as e:
            logging.error('保存用户头像信息失败')
            return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])
        return jsonify(code=RET.OK, url=current_app.config['QINIU_URL'] + avatar_url)

    elif 'name' in data_dict:
        # 2 修改用户名
        user_name = data_dict.get('name')

        if not user_name:
            return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

        # 判断用户名是否存在
        try:
            if User.query.filter_by(name=user_name).count():
                return jsonify(code=RET.DATAEXIST, msg='用户名已存在')
        except Exception as e:
            logging.error('查询数据库失败')
            return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])

        # 保存数据
        try:
            user.name = user_name
            user.add_update()
        except Exception as e:
            logging.error('保存用户名失败')
            return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])

        return jsonify(code=RET.OK, msg='OK')

    else:
        return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])


@user_blueprint.route('/user/auth',  methods=['PUT'])
@is_login
def user_auth():

    data_dict = request.form
    id_name = data_dict.get('id_name')
    id_card = data_dict.get('id_card')
    user = g.user

    if not all([id_name,id_card]):
        return jsonify(code=RET.PARAMERR,msg=ret_map[RET.DATAERR])

    if not re.match(r'^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',id_card):
        return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

    try:
        if User.query.filter_by(id_card=id_card).count():
            return jsonify(code=RET.DATAEXIST, msg=ret_map[RET.DATAEXIST])
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])
    try:

        user.id_name = id_name
        user.id_card = id_card

        user.add_update()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.PARAMERR,msg=ret_map[RET.PARAMERR])

    return jsonify(code=RET.OK,msg=ret_map[RET.OK])

@user_blueprint.route('/user/auth')
@is_login
def auth_roll():
    user = g.user

    return jsonify(user.to_auth_dict())

"""
请求路径: /passport/login
请求方式: POST
请求参数: mobile,password
返回值: errno, errmsg
"""

@user_blueprint.route('/user/session', methods=['POST'])
def login():
    # 获取参数
    dict = request.form
    mobile = dict.get("mobile")
    passwd = dict.get("password")

    # 校验参数

    user = User.query.filter_by(phone=mobile).first()
    if not user or not user.check_pwd(passwd):
        return jsonify(code=RET.DBERR, msg="用户查询错误")
    # 状态保持
    session['user_id'] = user.id
    # 返回响应
    return jsonify(code=RET.OK,msg="登陆成功")